package com.jfinal.aceadmin.index;

import java.io.File;
import java.util.UUID;

import com.jfinal.aceadmin.util.ConstantKit;
import com.jfinal.aceadmin.vo.AttachmentVo;
import com.jfinal.core.Controller;
import com.jfinal.ext.route.ControllerBind;
import com.jfinal.kit.JsonKit;
import com.jfinal.kit.PropKit;
import com.jfinal.upload.UploadFile;

@ControllerBind(controllerKey = "/admin",viewPath="/admin/index/")
public class IndexController extends Controller {
	public void index() {
		String name = getSessionAttr("name");
		setAttr("name", name);
		render("index.html");
	}
	
	public void upload() {
		UploadFile uploadFile = getFile("attachments");
		String name = uploadFile.getFileName();
		String fileName = UUID.randomUUID().toString()
				+ name.substring(name.lastIndexOf("."), name.length());
		int type = getParaToInt("type");
		if(ConstantKit.AVATAR == type){
			String iconDir = PropKit.use("server_config.properties").get("iconDir");
			File savedFile = new File(iconDir + "/" + fileName);
			uploadFile.getFile().renameTo(savedFile);
		}else if(ConstantKit.ATTACHMENT == type){
			String attachmentDir = PropKit.use("server_config.properties").get("attachmentDir");
			File savedFile = new File(attachmentDir + "/" + fileName);
			uploadFile.getFile().renameTo(savedFile);
			AttachmentVo attachmentVo = new AttachmentVo();
			attachmentVo.setFileName(fileName);
			attachmentVo.setFileSize(savedFile.length());
			setAttr("attachment", JsonKit.toJson(attachmentVo));
		}
		setAttr("fileName", fileName);
		setAttr("success", true);
		renderJson();
	}
}
